package com.yzh.wanandroid.vm

import android.app.Application
import android.util.Log
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.paging.Pager
import androidx.paging.PagingConfig
import com.yzh.wanandroid.base.BaseFragmentViewModel
import com.yzh.wanandroid.model.NetWorkData
import com.yzh.wanandroid.model.StateData
import com.yzh.wanandroid.network.retrofit.RetrofitFactory
import com.yzh.wanandroid.network.retrofit.api.DataServer
import com.yzh.wanandroid.network.retrofit.responsebean.BaseData
import com.yzh.wanandroid.network.retrofit.responsebean.TopBannerData
import com.yzh.wanandroid.repository.BaseRepository
import com.yzh.wanandroid.repository.datasource.ListRepository
import com.yzh.wanandroid.utils.PAGER_HOME
import com.yzh.wanandroid.utils.SUCCESS

class HomePagerFragmentVm(application: Application) : BaseFragmentViewModel(application) {

    private val TAG = "HomePagerFragmentVm"

    var loadingBanner = MutableLiveData<StateData<List<TopBannerData>>>()

    var netWorkData = NetWorkData()

    override fun onCreate(owner: LifecycleOwner) {
        super.onCreate(owner)
        checkNetData()
        loadTopBanner(owner)
    }

    /**
     * 检查网络状态
     */
    fun checkNetData() {
        netWorkData.hasNetWork = netWorkCheck()
    }

    /**
     * 加载首页banner
     */
    fun loadTopBanner(owner: LifecycleOwner) {
        BaseRepository<BaseData<List<TopBannerData>>>(owner) {
            loadData {
                Log.i(TAG, "onCreate loadData")
                RetrofitFactory.createApi(DataServer::class.java).getTopBanner()
            }.success {
                Log.i(TAG, "onCreate ${it.data}")
                loadingBanner.value = StateData(SUCCESS, data = it.data)
            }
        }
    }

    /**
     * 通过paging3加载文章列表
     */
    fun getData() = Pager(PagingConfig(pageSize = 1)) {
        ListRepository(PAGER_HOME)
    }.flow
}